<template>
  <view class="recent-cards">
    <block v-if="singleProgram">
      <ProgramCard
        :program="attrs.programs[0]"
        :disabled="isOffline === true || (attrs.disabled && !usePlainDisabled)"
        :plain-disabled="attrs.disabled && usePlainDisabled"
        :action-name="attrs.actionName"
        @action="attrs.onAction?.(attrs.programs[0])"
      />
    </block>
    <block v-else>
      <swiper class="recent-swiper" :current="recentIndex" @change="onRecentSwiperChange">
        <swiper-item class="recent-swiper-item" v-for="(program, index) in attrs.programs" :key="index">
          <view class="program-card-wrap">
            <ProgramCard
              :program="program"
              :disabled="isOffline === true || (attrs.disabled && !usePlainDisabled)"
              :plain-disabled="attrs.disabled && usePlainDisabled"
              :action-name="attrs.actionName"
              @action="attrs.onAction?.(program)"
            />
          </view>
        </swiper-item>
      </swiper>
      <view class="recent-swiper-dots">
        <view
          v-for="(_, index) in attrs.programs"
          :key="index"
          class="dot"
          :class="{ active: index === recentIndex }"
        />
      </view>
    </block>
  </view>
</template>

<script setup lang="ts">
import type { BaseController } from '@/controller/BaseAppliance/definition'
import { useControlState } from '@/controller/BaseAppliance/useControl'
import ProgramCard from '@/pages/appliance/components/programCard.vue'
import { HistoryProgramTypes, type HistoryProgram, type HistoryProgramOption } from '@/api/appliance'
import { useI18n } from 'vue-i18n'
import { showLoading } from '@/utils/mpHelper'
import { trackEvent, TrackType } from '@/dataReport/tracks'
import { orderPermanentInfo } from '@/utils/deviceMessageSubscribe/deviceMessage'
import { safeTrack } from '@/dataReport/dataReportUtil'

const props = defineProps<{
  control: BaseController.Control
  type: HistoryProgramTypes
  usePlainDisabled?: boolean
  singleProgram?: boolean // 是否只显示一个程序
  preventAction?: boolean // 是否阻止默认操作
}>()
const emit = defineEmits<{
  (e: 'action', payload: { type: HistoryProgramTypes; program: HistoryProgram }): void
}>()

const i18n = useI18n()
const { isOffline, startDisabled, orderDisabled } = useControlState(props.control)

const recentIndex = ref(0)
function onRecentSwiperChange(e: WechatMiniprogram.SwiperChange) {
  recentIndex.value = e.detail.current
}

type Attrs = {
  programs: HistoryProgram[]
  disabled: boolean
  actionName: string
  onAction?: (program: HistoryProgram) => void
}
const attrs = computed<Attrs>(() => {
  const attrs: Attrs = {
    programs: [],
    disabled: false,
    actionName: '',
  }
  switch (props.type) {
    case HistoryProgramTypes.StartedProgram: {
      attrs.programs = props.control.store.recentStartedPrograms
      attrs.disabled = startDisabled.value
      attrs.actionName = i18n.t('Appliance.StartProgram.Button.Text')
      attrs.onAction = (program) => {
        safeTrack(() => {
          trackEvent(
            'Appliance.StartProgram.Button.Text',
            {},
            TrackType.ApplianceDetail,
            'Appliance.RecentlyUsed.StartProgram.Button.Text'
          )
        })
        !props.preventAction && onRecentStartNow(program)
        emit('action', { type: props.type, program })
      }
      break
    }
    case HistoryProgramTypes.OrderedProgram: {
      attrs.programs = props.control.store.recentOrderedPrograms
      attrs.disabled = orderDisabled.value
      attrs.actionName = i18n.t('Appliance.OrderProgram.Button.Text')
      attrs.onAction = (program) => {
        !props.preventAction && onRecentOrderNow(program)
        emit('action', { type: props.type, program })
      }
      break
    }
  }
  if (props.singleProgram) {
    attrs.programs = attrs.programs.slice(0, 1)
  }
  return attrs
})

async function onRecentStartNow(program: HistoryProgram) {
  const store = props.control.store
  trackEvent('Appliance.RecentlyUsed.StartProgram.Button.Text', {}, TrackType.ApplianceDetail)

  // 永久消息订阅
  try {
    await orderPermanentInfo(props.control.store._datasource.haId)
  } catch (e) {
    console.error(e)
  }

  await showLoading(async () => {
    // 选择程序
    await store.setCurrentProgram(program.key)
    // 过滤支持的Option
    const validOptions = await loadValidOptions(program)
    // 启动程序
    await props.control.store.startProgramNow(program, validOptions, 'Appliance.RecentlyUsed.StartProgram.Button.Text')
  }, i18n.t('APP.Common.Submitting.Text'))
}

async function onRecentOrderNow(program: HistoryProgram) {
  // trackEvent('Appliance.RecentlyUsed.StartProgram.Button.Text', {}, TrackType.ApplianceDetail)
  const store = props.control.store
  await showLoading(async () => {
    // 选择程序
    await store.setCurrentProgram(program.key)
    // 过滤支持的Option
    const validOptions = await loadValidOptions(program)
    // 预约程序
    await props.control.store.orderProgramNow(program, validOptions)
  }, i18n.t('APP.Common.Submitting.Text'))
}

async function loadValidOptions(program: HistoryProgram): Promise<HistoryProgramOption[]> {
  const store = props.control.store
  // 查询Option
  await store.loadAvailableParameter()
  const availableOptions = store.availableParameter?.options || []
  return program.options.filter((historyOption) => {
    return availableOptions.some((availableOption) => availableOption.key === historyOption.key)
  })
}
</script>

<style scoped lang="less">
.recent-cards {
  .recent-swiper {
    height: 156rpx;
    .recent-swiper-item {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .recent-swiper-dots {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 8rpx;
    .dot {
      width: 12rpx;
      height: 4rpx;
      background-color: #d5d7da;
      &.active {
        background-color: var(--dark-color);
      }
      + .dot {
        margin-left: 6rpx;
      }
    }
  }
  .program-card-wrap {
    width: 100%;
    padding: 0 32rpx;
    box-sizing: border-box;
  }
}
</style>
